package com.kaiwukj.android.ufamily.mvp.ui.page.service.fee;

import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.GsonUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackActivity;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayInfo;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.PayFeeCancelRequest;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.PropertyFeeResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.AlipayResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.PayFeeHouseAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.PayFeeUrl;

/**
 * @author Charles
 * @date 2019/10/15.
 * description：Kaiwu
 */
@Route(path = PayFeeUrl)
public class PayFeeActivity extends BaseSwipeBackActivity<PayFeePresenter> implements ServiceContract.PropertyView {

    @BindView(R.id.qtb_view)
    QMUITopBar qtbView;
    @BindView(R.id.tv_place)
    TextView tvPlace;
    @BindView(R.id.rv_room)
    RecyclerView rvRoom;
    @BindView(R.id.tv_pay_amount)
    TextView tvPayAmount;
    @BindView(R.id.tv_pay_company)
    TextView tvPayCompany;
    @BindView(R.id.tv_pay_name)
    TextView tvPayName;
    @BindView(R.id.tv_owner_name)
    TextView tvOwnerName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_pay_final)
    EditText etPayFinal;
    @BindView(R.id.tv_pay)
    Button tvPay;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.tv_rv_text)
    TextView tvRvText;

    private PayFeeHouseAdapter mAdapter;

    private int checkedPos = 0;


    @Autowired
    int type = 1;//默认物业费
//    1 物业缴费 2 车位缴费 3 车库缴费

    private String tradeNo;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_pay_fee;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

        mAdapter = new PayFeeHouseAdapter();
        initRecyclerView();
        mAdapter.setOnCheckedChangedListener(pos -> {
            checkedPos = pos;
            loadData(mAdapter.getItem(pos));
        });
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        if (getApp().getUserInfo() != null) {
            tvPlace.setText(getApp().getUserInfo().getLastCommunityName());
        }

        if (!getApp().getUserInfo().isCommunityOwner()) {
            showMessage("您没有需缴费的账单");
            new Handler().postDelayed(this::onBackPressedSupport, 1500);
            return;
        }

        qtbView.setTitle(type == 1 ? "物业缴费" : "车位缴费");
        tvRvText.setText(type == 1 ? "房间号" : "车位号");
        ivIcon.setImageResource(type == 1 ? R.mipmap.icon_pay_fee_head : R.mipmap.icon_car_p);
        qtbView.addLeftBackImageButton().setOnClickListener(view -> finish());

        mPresenter.requestPayFeeList();

        tvPay.setOnClickListener(view -> {

            new QMUIBottomSheet.BottomListSheetBuilder(this)
                    .addItem(ContextCompat.getDrawable(this, R.mipmap.ic_pay_alipay), "支付宝")
                    .addItem(ContextCompat.getDrawable(this, R.mipmap.ic_pay_wechat), "微信")
                    .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                        if (checkedPos >= 0) {
                            if (position == 0) {
                                mPresenter.payByAli(mAdapter.getItem(checkedPos).getReferenceId(), this);
                            } else {
                                mPresenter.payByWechat(mAdapter.getItem(checkedPos).getReferenceId(), this);
                            }
                        }
                        dialog.dismiss();
                    }).build().show();

        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent payEvent) {
        if (payEvent.isSuccess()) {
            showMessage("支付成功");
            new Handler().postDelayed(this::finish, 800);
        } else if (payEvent.getDesc().equals("支付已取消")) {
            mPresenter.cancelOrder(new PayFeeCancelRequest(tradeNo));
        } else {
            showMessage(payEvent.getDesc());
        }
    }

    private void initRecyclerView() {
        rvRoom.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rvRoom.setAdapter(mAdapter);
    }

    private void loadData(PropertyFeeResult data) {
        //tvPlace.setText(UserStore.getCommunityName());
        tvPayAmount.setText(String.format("%s元", data.getPayableAmount()));
        tvPayCompany.setText(data.getEstateName());
        tvPayName.setText(data.getOwnerPhone());
        tvOwnerName.setText(data.getOwnerName());
        tvAddress.setText(data.getAddress());
        etPayFinal.setText(String.valueOf(data.getPayableAmount()));
    }

    @Override
    public void onPropertyResult(List<PropertyFeeResult> results) {
        if (results.size() > 0) {
            mAdapter.setList(results);
            mAdapter.check(checkedPos);
        } else {
            showMessage("您没有需缴费的账单");
            new Handler().postDelayed(this::finish, 800);
        }
    }

    @Override
    public void onWXPayResult(Map<String, Object> payResult) {

        PayInfo payInfo = GsonUtils.fromJson(GsonUtils.toJson(payResult), PayInfo.class);
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constant.WX_APP_ID);
        if (msgApi.isWXAppInstalled()) {
            msgApi.sendReq(payInfo.getPayReq());
            tradeNo = payInfo.getTradeNo();
        } else {
            showMessage(getString(R.string.please_install_wechat));
        }

    }

    @Override
    public void onAliPayResult(Map<String, Object> result) {
        subscribe(Observable.create((ObservableOnSubscribe<PayResult>) emitter -> {
            String sign = GsonUtils.toJson(result);
            AlipayResult payObj = GsonUtils.fromJson(sign, AlipayResult.class);
            PayTask payTask = new PayTask(this);
            Map<String, String> map = payTask.payV2(payObj.getSign(), true);
            emitter.onNext(new PayResult(map));
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payResult -> {
                    if ("9000".equals(payResult.getResultStatus())) {
                        EventBus.getDefault().post(new PayEvent(PayEvent.SUCCESS, 0, "支付成功"));
                    } else if ("6001".equals(payResult.getResultStatus())) {
                        showMessage("支付已取消");
                    } else {
                        EventBus.getDefault().post(new PayEvent(PayEvent.FAILED, 0, "支付失败"));
                    }
                }));

    }
}
